<template>
  <div id="contestListView">
    <a-row :gutter="[16, 16]" style="margin-bottom: 16px">
      <a-col :span="24">
        <a-card>
          <template #title>
            <a-space>
              <a-icon-calendar />
              <span>比赛列表</span>
            </a-space>
          </template>
          <template #extra>
            <a-space>
              <a-select
                v-model="searchParams.status"
                placeholder="选择比赛状态"
                style="width: 150px"
                allow-clear
                @change="loadData"
              >
                <a-option :value="0">未开始</a-option>
                <a-option :value="1">进行中</a-option>
                <a-option :value="2">已结束</a-option>
              </a-select>
              <a-button type="primary" @click="createContest" v-if="isAdmin">
                创建比赛
              </a-button>
            </a-space>
          </template>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="[16, 16]">
      <a-col
        v-for="contest in contestList"
        :key="contest.id"
        :xs="24"
        :sm="12"
        :md="8"
        :lg="6"
      >
        <a-card
          :class="getContestCardClass(contest)"
          hoverable
          @click="viewContest(contest)"
        >
          <template #cover>
            <div class="contest-cover">
              <a-tag :color="getStatusColor(contest.status)" class="status-tag">
                {{ getStatusText(contest.status) }}
              </a-tag>
              <div class="contest-time">
                <div>{{ formatTime(contest.startTime) }}</div>
                <div>至</div>
                <div>{{ formatTime(contest.endTime) }}</div>
              </div>
            </div>
          </template>
          <template #title>
            <div class="contest-title">
              <a-icon-trophy style="color: #ffd700; margin-right: 8px" />
              {{ contest.title }}
            </div>
          </template>
          <template #extra>
            <a-space>
              <a-tag v-if="contest.isPublic" color="green">公开</a-tag>
              <a-tag v-else color="orange">私有</a-tag>
              <a-tag v-if="contest.isRegistered" color="blue">已报名</a-tag>
            </a-space>
          </template>
          <div class="contest-content">
            <p class="contest-description">{{ contest.description }}</p>
            <div class="contest-info">
              <div class="info-item">
                <a-icon-user />
                <span>题目数: {{ contest.problems?.length || 0 }}</span>
              </div>
              <div class="info-item">
                <a-icon-clock-circle />
                <span>时长: {{ getContestDuration(contest) }}</span>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <a-row v-if="total > 0" style="margin-top: 16px">
      <a-col :span="24">
        <a-pagination
          v-model:current="searchParams.page"
          v-model:page-size="searchParams.size"
          :total="total"
          show-total
          show-size-changer
          @change="onPageChange"
          @page-size-change="onPageSizeChange"
        />
      </a-col>
    </a-row>

    <!-- 创建比赛对话框 -->
    <a-modal
      v-model:visible="createModalVisible"
      title="创建比赛"
      width="800px"
      @ok="handleCreateContest"
      @cancel="createModalVisible = false"
    >
      <a-form :model="createForm" layout="vertical">
        <a-form-item label="比赛标题" required>
          <a-input v-model="createForm.title" placeholder="请输入比赛标题" />
        </a-form-item>
        <a-form-item label="比赛描述">
          <a-textarea
            v-model="createForm.description"
            placeholder="请输入比赛描述"
            :rows="3"
          />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="开始时间" required>
              <a-date-picker
                v-model="createForm.startTime"
                show-time
                placeholder="选择开始时间"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结束时间" required>
              <a-date-picker
                v-model="createForm.endTime"
                show-time
                placeholder="选择结束时间"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="比赛类型">
              <a-select
                v-model="createForm.ruleType"
                placeholder="选择比赛类型"
              >
                <a-option :value="0">ACM</a-option>
                <a-option :value="1">OI</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="访问权限">
              <a-switch
                v-model="createForm.isPublic"
                checked-children="公开"
                un-checked-children="私有"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item v-if="!createForm.isPublic" label="访问密码">
          <a-input v-model="createForm.password" placeholder="请输入访问密码" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import message from "@arco-design/web-vue/es/message";
import moment from "moment";
import { ContestControllerService } from "../../generated";
import type { Contest } from "../../generated";

const router = useRouter();
const store = useStore();

// 数据
const contestList = ref<Contest[]>([]);
const total = ref(0);
const searchParams = ref({
  page: 1,
  size: 12,
  status: undefined as number | undefined,
});

// 创建比赛相关
const createModalVisible = ref(false);
const createForm = ref({
  title: "",
  description: "",
  startTime: null,
  endTime: null,
  ruleType: 0,
  isPublic: true,
  password: "",
});

// 计算属性
const isAdmin = computed(() => {
  return store.state.user?.loginUser?.userRole === "admin";
});

// 加载比赛列表
const loadData = async () => {
  try {
    const res = await ContestControllerService.getContestListUsingGet(
      searchParams.value.page,
      searchParams.value.size,
      searchParams.value.status
    );
    if (res.code === 0) {
      contestList.value = res.data.records || [];
      total.value = res.data.total || 0;
    } else {
      message.error("加载失败，" + res.message);
    }
  } catch (error) {
    message.error("加载失败");
  }
};

// 分页处理
const onPageChange = (page: number) => {
  searchParams.value.page = page;
  loadData();
};

const onPageSizeChange = (pageSize: number) => {
  searchParams.value.size = pageSize;
  searchParams.value.page = 1;
  loadData();
};

// 比赛状态处理
const getStatusText = (status: number) => {
  const statusMap = {
    0: "未开始",
    1: "进行中",
    2: "已结束",
  };
  return statusMap[status as keyof typeof statusMap] || "未知";
};

const getStatusColor = (status: number) => {
  const colorMap = {
    0: "blue",
    1: "green",
    2: "gray",
  };
  return colorMap[status as keyof typeof colorMap] || "default";
};

const getContestCardClass = (contest: Contest) => {
  const baseClass = "contest-card";
  if (contest.status === 1) {
    return `${baseClass} contest-running`;
  }
  return baseClass;
};

// 时间格式化
const formatTime = (time: string) => {
  return moment(time).format("MM-DD HH:mm");
};

const getContestDuration = (contest: Contest) => {
  const start = moment(contest.startTime);
  const end = moment(contest.endTime);
  const duration = moment.duration(end.diff(start));
  const hours = Math.floor(duration.asHours());
  const minutes = duration.minutes();
  return `${hours}小时${minutes}分钟`;
};

// 查看比赛详情
const viewContest = (contest: Contest) => {
  router.push({
    path: `/contest/${contest.id}`,
  });
};

// 创建比赛
const createContest = () => {
  createModalVisible.value = true;
};

const handleCreateContest = async () => {
  try {
    const contestData = {
      ...createForm.value,
      startTime: createForm.value.startTime?.toISOString(),
      endTime: createForm.value.endTime?.toISOString(),
    };

    const res = await ContestControllerService.createContestUsingPost(
      contestData
    );
    if (res.code === 0) {
      message.success("创建成功");
      createModalVisible.value = false;
      loadData();
      // 重置表单
      createForm.value = {
        title: "",
        description: "",
        startTime: null,
        endTime: null,
        ruleType: 0,
        isPublic: true,
        password: "",
      };
    } else {
      message.error("创建失败，" + res.message);
    }
  } catch (error) {
    message.error("创建失败");
  }
};

// 页面加载
onMounted(() => {
  loadData();
});
</script>

<style scoped>
#contestListView {
  max-width: 1400px;
  margin: 0 auto;
  padding: 16px;
}

.contest-card {
  height: 100%;
  transition: all 0.3s;
}

.contest-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.contest-running {
  border: 2px solid #52c41a;
}

.contest-cover {
  position: relative;
  height: 120px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
}

.status-tag {
  position: absolute;
  top: 8px;
  right: 8px;
}

.contest-time {
  text-align: center;
  font-size: 12px;
}

.contest-title {
  font-weight: bold;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.contest-content {
  margin-top: 8px;
}

.contest-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.contest-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>
